//
//  RGContactsViewController.m
//  RedGrass
//
//  Created by wukong on 2019/2/23.
//  Copyright © 2019年 hongcaosp. All rights reserved.
//

#import "RGContactsViewController.h"
#import "RGFrendsContacts.h"
#import "HttpRequest.h"
#import "RGMessageContactModel.h"
#import "RGMessageFunsCell.h"
#import "RGMessageInterfaceBulider.h"
#import "SDContactsHelper.h"

@interface RGContactsViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataList;

@end

@implementation RGContactsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showBackButton];
    self.customNavBar.title = @"通信录好友";
    self.customContentView.backgroundColor = [UIColor blackColor];
    [self.customContentView addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    if (![SDContactsHelper canAccessContacts]) {
        [self showUserDenied];
    }else{
        [self gainContacts];
    }
}

//弹出无法访问警告框
- (void)showUserDenied {
    
    NSString *message = @"您没有权限访问通讯录\n\n请到“设置-隐私-通讯录”里\n允许”悠趣“访问";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sure];
    [self presentViewController:alert animated:true completion:nil];
}

-(void)gainContacts{
    [self showLoading:@""];
    AA_WEAK_MAKE(self)weakSelf = self;
    [SDContactsHelper fetchContacts:^(NSArray <SDContacter *> *contacts, BOOL success) {
        if (success) {
            
            NSMutableArray *tempArr = [NSMutableArray array];
            for (NSInteger index = 0 ; index < contacts.count; index ++) {
                SDContacter *sdc = contacts[index];
                if([sdc.phone length]){
                    [tempArr addObject:sdc.phone];
                }
            }
            if([tempArr count]){
              
                [weakSelf updatePhoneListWithArr:tempArr];
            }else{
                  [weakSelf dismissLoading];
            }
        }else{
            [weakSelf dismissLoading];
            [weakSelf showTextMessageWithMessage:@"通讯录获取失败"];
        }
    }];
}

-(void) updatePhoneListWithArr:(NSArray *)phones{
    
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/user/directoriesFriends"];
    AA_WEAK_MAKE(self) weakSelf = self;
    if(phones.count == 0){
        return;
    }
    NSString *moblie = [phones componentsJoinedByString:@","];
    RGUserInfoModel *user = [RGUserInfoModel getUserInfo];
    NSDictionary *dic = @{@"token":SafeStr(user.token),
                          @"mobile":moblie
                          };
    [quest post:dic success:^(id data) {
        weakSelf.dataList = [RGMessageContactModel arrayOfModelsFromDictionaries:[data objectForKey:@"directoriesFriends"] error:nil];
        [weakSelf.tableView reloadData];
        [weakSelf dismissLoading];
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf showTextMessageWithMessage:message];
    }];
    
}

#pragma mark - tableView delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataList.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RGMessageFunsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"funsCell"];
    RGMessageContactModel *findFriendModel = [self.dataList objectAtIndex:indexPath.row];
    cell.findFriendModel = findFriendModel;
    [cell updateUIStyleWhenShowContactUser];
    [cell setAddOrCancelBlock:^(UIButton * _Nonnull btn) {
        if (btn.isSelected) {
            HttpRequest *quest = [HttpRequest buildRequest:url_cancel];
            NSDictionary *params = [RGMessageInterfaceBulider buildUserCancel:findFriendModel.ID];
            AA_WEAK_MAKE(self) weakSelf = self;
            [quest post:params success:^(id data) {
                btn.selected = NO;
                btn.backgroundColor = UICOLOR_WITH_RGBINT(0xf73152);
            }fail:^(NSInteger code, NSString *message) {
                [weakSelf showTextMessageWithMessage:@"操作失败，请重试"];
            }];
        }else {
            HttpRequest *quest = [HttpRequest buildRequest:url_add];
            NSDictionary *params = [RGMessageInterfaceBulider buildUserAdd:findFriendModel.ID];
            AA_WEAK_MAKE(self) weakSelf = self;
            [quest post:params success:^(id data) {
                btn.selected = YES;
                btn.backgroundColor = UICOLOR_WITH_RGBINT(0x716d7f);
            }fail:^(NSInteger code, NSString *message) {
                [weakSelf showTextMessageWithMessage:@"操作失败，请重试"];
            }];
        }
    }];
    return cell;
}



#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UICOLOR_WITH_RGBINT(0x000000);
        [_tableView registerClass:[RGMessageFunsCell class] forCellReuseIdentifier:@"funsCell"];
    }
    return _tableView;
}


@end
